import { createSlice } from "@reduxjs/toolkit";
const cartSlice = createSlice({
    name: 'cart',
    initialState: {
        cartList: []
    },
    reducers: {
        joinCart(state, { payload }) {
            const info = state.cartList.find(v => v.id === payload.id)
            if (info) {
                info.buyNum += 1
            } else {
                state.cartList.unshift({
                    ...payload,
                    buyNum: 1
                })
            }
        },
        // 更改购买数量
        changeBuyNum(state, { payload }) {
            // payload:{id:唯一标识，num:操作的数量 1：加1  -1 加-1}
            // 根据payload.id找到下标
            const index = state.cartList.findIndex(v => v.id === payload.id);
            state.cartList[index].buyNum += payload.num;
            if (state.cartList[index].buyNum === 0) {
                state.cartList.splice(index, 1);
            }
        }
    }
})
const { joinCart, changeBuyNum } = cartSlice.actions

export { cartSlice, joinCart, changeBuyNum}